package com.example.artgallery

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.app.AlertDialog
import android.widget.Toast
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.core.content.ContextCompat
import com.example.artgallery.repository.ArtRepository
import com.example.artgallery.ui.AddArtworkScreen
import com.example.artgallery.ui.FolderScreen
import com.example.artgallery.ui.GalleryScreen
import com.example.artgallery.ui.theme.ArtGalleryTheme
import java.io.File

class MainActivity : ComponentActivity() {
    private val repository by lazy { ArtRepository(File(filesDir, "data")) }
    private var selectedImageUri by mutableStateOf<Uri?>(null)
    
    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted ->
        if (isGranted) {
            openImagePicker()
        }
    }

    private val pickImageLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        result.data?.data?.let { uri ->
            selectedImageUri = uri
        }
    }

    private fun openImagePicker() {
        val intent = Intent(Intent.ACTION_GET_CONTENT).apply {
            type = "image/*"
        }
        pickImageLauncher.launch(intent)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ArtGalleryTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    AppContent(
                        repository = repository,
                        onAddArtwork = {
                            when {
                                ContextCompat.checkSelfPermission(
                                    this,
                                    Manifest.permission.READ_EXTERNAL_STORAGE
                                ) == PackageManager.PERMISSION_GRANTED -> {
                                    openImagePicker()
                                }
                                else -> {
                                    requestPermissionLauncher.launch(
                                        Manifest.permission.READ_EXTERNAL_STORAGE
                                    )
                                }
                            }
                        },
                        selectedImageUri = selectedImageUri,
                        onImageSelected = { uri ->
                            selectedImageUri = uri
                        }
                    )
                }
            }
        }
    }
}

@Composable
private fun AppContent(
    repository: ArtRepository,
    onAddArtwork: () -> Unit,
    selectedImageUri: Uri?,
    onImageSelected: (Uri?) -> Unit
) {
    var currentScreen by remember { mutableStateOf<Screen>(Screen.Folders) }
    var currentFolder by remember { mutableStateOf<String?>(null) }
    
    when (currentScreen) {
        Screen.Folders -> {
            FolderScreen(
                repository = repository,
                onFolderSelected = { folder ->
                    currentFolder = folder
                    currentScreen = Screen.Gallery
                },
                onAddArtwork = {
                    currentScreen = Screen.AddArtwork
                },
                onDeleteFolder = { folder ->
                    AlertDialog.Builder(this)
                        .setTitle("删除文件夹")
                        .setMessage("确定要删除文件夹 '$folder' 及其所有内容吗？")
                        .setPositiveButton("删除") { _, _ ->
                            if (repository.deleteFolder(folder)) {
                                Toast.makeText(this, "已删除文件夹", Toast.LENGTH_SHORT).show()
                            } else {
                                Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show()
                            }
                        }
                        .setNegativeButton("取消", null)
                        .show()
                }
            )
        }
        Screen.Gallery -> {
            GalleryScreen(
                artworks = repository.getArtworksByFolder(currentFolder!!),
                onBack = { currentScreen = Screen.Folders }
            )
        }
        Screen.AddArtwork -> {
            AddArtworkScreen(
                onBack = { currentScreen = Screen.Folders },
                onAddArtwork = onAddArtwork,
                selectedImageUri = selectedImageUri,
                onImageSelected = onImageSelected,
                onSubmit = { title, folder ->
                    selectedImageUri?.let { uri ->
                        val artwork = Artwork(
                            id = System.currentTimeMillis(),
                            title = title,
                            folder = folder,
                            imagePath = uri.toString(),
                            createDate = System.currentTimeMillis().toString()
                        )
                        repository.addArtwork(artwork)
                        currentScreen = Screen.Folders
                    }
                }
            )
        }
    }
}

private sealed class Screen {
    object Folders : Screen()
    object Gallery : Screen()
    object AddArtwork : Screen()
}